package com.zhiying.controller;

import java.awt.image.BufferedImage;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import com.zhiying.domain.CMS_Menu;
import com.zhiying.domain.CMS_User;
import com.zhiying.service.LoginService;
import com.zhiying.service.MenuService;
import com.zhiying.until.code.Code;
import com.zhiying.until.ipadderss.IpAddress;


@EnableAutoConfiguration
@ComponentScan(basePackages={"com.zhiying.service","com.zhiying.controller","com.zhiying.domain","com.zhiying.jpa","com.zhiying.config"})//添加的注解
@Controller
public class ShiroController {

	@Autowired
	private LoginService loginService;
	
	@Autowired
	private Producer captchaProducer;
	
	@Autowired
	private MenuService menuService;
	
	IpAddress ip;
	//获取本机ip
//	@Autowired
//	RedisService redisService;
	
	@ResponseBody
	@RequestMapping("/shiro")
	public List shiro(HttpServletRequest req) {
//		User user=new User();
//		user.setId((long) 3);
//		user.setName("fff");
//		user.setPassword(45);
//		loginService.insertUser(user);
		Pageable pageable = new PageRequest(0,10);
//		if(redisService.exists("keys")==true) {
//			return (List<User>) redisService.get("keys",this.getClass());
//		}else {
//			redisService.set("keys",loginService.showUser(pageable));
//		}
//	
		//(pageNO-1)*pageNum
//		loginService.update();
		return loginService.showUser(pageable,"f",4);
	}
	
	@ResponseBody
	@RequestMapping("/del")
	public String del() {
		loginService.delUser();
		return "del success";
	}
	
	@ResponseBody
	@RequestMapping("/update")
	public String update() {
		loginService.update();
		return "update success";
	}

	@RequestMapping("/index")
	public String index() {
		
		return "index";
	}
	
	@RequestMapping("/login")
	public String flyShoppingAdmin(HttpServletRequest req) {
		/*
		 * List<CMS_User> list=menuService.selectLoginLog();
		 * System.out.println(list.get(0).getUserName());
		 */
		System.out.println("本机ip"+ip.getIpAddr(req));
		System.out.println("获取当前用户游览器信息"+ip.getHeader(req));
		System.out.println("获取当前用户游览器型号"+ip.getUserBrowser(req));
		System.out.println("获取当前用户系统型号"+ip.getUserOperatingSystem(req));
		return "login/admin_login";
	}
	
	/**
	 * GET 验证码
	 */
//	@ApiOperation(value = "登录验证码", notes = "登录验证码")  
	@GetMapping(value = "/captcha-image")
	public ModelAndView getKaptchaImage(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// 禁止服务器端缓存
		response.setDateHeader("Expires", 0);
		
		// 设置标准的 HTTP/1.1 no-cache headers.  
		response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
		
		// 设置IE扩展 HTTP/1.1 no-cache headers (use addHeader).  
		response.addHeader("Cache-Control", "post-check=0, pre-check=0");
		
		// 设置标准 HTTP/1.0 不缓存图片  
		response.setHeader("Pragma", "no-cache");
		
		// 返回一个 jpeg 图片，默认是text/html(输出文档的MIMI类型)  
		response.setContentType("image/jpeg");
		
		// 为图片创建文本  
		String capText = captchaProducer.createText();
		
		// 将文本保存在session中，这里就使用包中的静态变量吧  
		request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);
		
		// 创建带有文本的图片  
		BufferedImage bi = captchaProducer.createImage(capText);
		ServletOutputStream out = response.getOutputStream();
		
		 // 图片数据输出  
		ImageIO.write(bi, "jpg", out);
		
		try {
			out.flush();
		} finally {
			out.close();
		}
		return null;
	}
	
	@RequestMapping("/loginIndex")
	@ResponseBody
	public Object info(HttpServletRequest req,CMS_User user) {
		
		Map map=new HashMap();
		boolean b=true;
		//判断验证码是否正确
		//1.获取session中的验证码
		String sessionRegisterCode=String.valueOf(req.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY));
		//2.获取输入的验证码
		String registerCode=req.getParameter("registerCode");
		if(!registerCode.trim().equalsIgnoreCase(sessionRegisterCode)) {
			System.out.println(registerCode+"==>"+sessionRegisterCode);
			map.put("code",10005);
			map.put("message",Code.message(10005));
		}else {
			System.out.println(registerCode+"==>"+sessionRegisterCode);
			Subject subject=SecurityUtils.getSubject();
	        UsernamePasswordToken userToken=new UsernamePasswordToken(user.getLoginName(),user.getLoginPassword());
	        try{
	            subject.login(userToken);
	            return "redirect:/all";
	        }catch (UnknownAccountException e){
//	            model.addAttribute("msg","用户名不存在");
	            map.put("code",10006);
				map.put("message",Code.message(10006));
				b=false;
				return map;
	        }catch (IncorrectCredentialsException e){
	        	map.put("code",10007);
				map.put("message",Code.message(10007));
				b=false;
				return map;
	        }finally {
	        	if(b) {
	        		map.put("code", 1);
		        	return map;
	        	}
	        }

		}
		return map;
		
		
		
		
	}
	@RequestMapping("/main")
	public String main(HttpServletRequest request) {
	    CMS_User user=loginService.getUserInfoByUserName((String)SecurityUtils.getSubject().getSession().getAttribute("loginName"));
		System.out.println(user.getOrganization().getOrganizationName());
	    List<CMS_Menu> Onelist=menuService.SelectMenuOneLIst();
		List<CMS_Menu> SonList=menuService.SelectMenusubmenuList();
		request.setAttribute("onemenus", Onelist);
		request.setAttribute("sonList", SonList);
		request.setAttribute("user", user);
		return "webfront/main";
		
	}
	
	/**
	 * GET 退出登录
	 * @return
	 */
	@GetMapping(value = "/logout")
	public String logout() {
		Subject subject = SecurityUtils.getSubject();
		subject.logout();
		return "redirect:/login";
	}
	
	
	
}
